package com.hfb.mashibing.alip8.spring.shardingsphere.config;

import java.util.Objects;
import lombok.extern.slf4j.Slf4j;

/**
 * 数据源上下文
 */
@Slf4j
public class DataSourceContextHolder {
    public static final String DATA_SOURCE = "datasource";
    public static final String DATA_SOURCE_01 = "datasource01";
    public static final String DATA_SOURCE_02 = "datasource02";
    public static final String DATA_SOURCE_03 = "datasource03";

    public static final ThreadLocal<String> CONTEXT_HOLODER = new ThreadLocal<>();

    public static void setDataSourceType(String dataSourceType) {
        if (Objects.isNull(dataSourceType)) {
            String msg = "dataSourceType 为空!";
            log.error(msg);
            throw new NullPointerException(msg);
        }
        log.info("设置数据源：{}", dataSourceType);
        CONTEXT_HOLODER.set(dataSourceType);
    }
    public static Object getDataSourceType() {
        return CONTEXT_HOLODER.get();
    }

    public static String setDataSourceType(Long id) {
        long res = id % DataSources.getDataSourceSize();
        String dataSource = DataSourceContextHolder.DATA_SOURCE_03;
        if (res == 0) {
            dataSource = DataSourceContextHolder.DATA_SOURCE_01;
        }else if (res == 1) {
            dataSource = DataSourceContextHolder.DATA_SOURCE_02;
        }
        DataSourceContextHolder.setDataSourceType(dataSource);
        return dataSource;
    }

}
